package com.yifeng.repo.micro.service.server.auth.sso.filter.config;

import com.yifeng.repo.micro.service.server.auth.sso.api.SsoClient;
import com.yifeng.repo.micro.service.server.auth.sso.filter.SsoFilter;
import com.yifeng.repo.micro.service.server.auth.sso.filter.cache.DegradableCache;
import com.yifeng.repo.micro.service.server.auth.sso.filter.context.SsoContextFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@EnableConfigurationProperties({SsoAuthProperties.class})
public class SsoAutoConfiguration  {
    private final SsoAuthProperties properties;
    private final ApplicationContext applicationContext;

    public SsoAutoConfiguration(SsoAuthProperties properties, ApplicationContext applicationContext) {
        this.properties = properties;
        this.applicationContext = applicationContext;
    }

    @Bean
    @ConditionalOnProperty(prefix = "yfcloud.micro.service.sso",name = "enable-request-context",havingValue = "true")
    public FilterRegistrationBean<SsoContextFilter> ssoContextFilter() {
        FilterRegistrationBean<SsoContextFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new SsoContextFilter());
        registration.addUrlPatterns("/*");
        registration.setName("SsoContextFilter");
        log.info("***** SsoContextFilter init success *****");
        return registration;
    }

    @Bean
    @ConditionalOnExpression("#{'${yfcloud.micro.service.sso.enable-auth}'.equals('true') || '${yfcloud.micro.service.sso.enable-request-auth}'.equals('true')}")
    public FilterRegistrationBean<SsoFilter> ssoFilter() {
        FilterRegistrationBean<SsoFilter> registration = new FilterRegistrationBean<>();
        SsoClient ssoClient;
        try {
            ssoClient = applicationContext.getBean(SsoClient.class);
        } catch (BeansException e) {
            throw new RuntimeException("ssoClient不存在");
        }
        DegradableCache degradableCache = new DegradableCache();
        degradableCache.setCacheSize(properties.getCacheSize());
        degradableCache.setCacheTime(properties.getCacheTime());
        registration.setFilter(new SsoFilter(degradableCache, ssoClient, properties.getPatterns(), properties.getIgnorePatterns()));
        registration.addUrlPatterns("/*");
        registration.setName("SsoFilter");
        registration.setOrder(1);
        log.info("***** SsoFilter init success *****");
        return registration;
    }

}
